require "BnbConstants"

--[[
Given a level in lua format as exported by the Tiled engine,
build a simpler level data called "collision map" and passed
to the underlying physics engine.
--]]

--[[
The map. This variable is overriden each time a new level is loaded in memory.
--]]
BnbCollisionMap = {}

local function checkMagic(levelMap)
  if levelMap == nil then return false end
  if levelMap.properties == nil then return false end
  if levelMap.properties.magic == nil then return false end
  return levelMap.properties.magic == BnbConstants.magic
end

local tileMap = {}

--[[
Given the tileset, build a map {Id->collision tags}.
--]]
local function buildTileMap(tileset)
  tileMap = {}
  local k = 1
  local tiles = tileset.tiles

  while (k <= #tiles)
  do
    local tile = tiles[k]
    local id = tile.id
    local tags = tile.properties.collisionTags
    -- TODO CHECK : check that the collision tag is not nil.
    tileMap[id] = tags
    k = k + 1
  end
end

local function buildCollisionMap (levelMap)
  if (not checkMagic(levelMap)) then return false end

  -- Gather some general information about the map
  -- TODO(REFACTOR) : see if those info are at the right place.
  BnbConstants.MapInfo.width = levelMap.width
  BnbConstants.MapInfo.height = levelMap.height
  BnbConstants.MapInfo.tile_width = levelMap.tilewidth
  BnbConstants.MapInfo.tile_height = levelMap.tileheight

  --[[
    Build a tile map to ease the conversion between tileId and
    the collision flags.
  --]]
  buildTileMap(levelMap.tilesets[1])

  -- New empty collision map
  local collisionMap = {}

  -- New empty layers
  for k,v in pairs(BnbConstants.layers_names) do
    collisionMap[v] = {}
  end
  
  local k = 1
  local layers = levelMap.layers

  while (k <= #layers)
  do
    local layer = layers[k]
    local name = layer.name
    -- TODO CHECK : check layer name validity.
    local collisionLayer = collisionMap[name]

    local data = layer.data
    local n = 1

    while (n <= #data)
    do
      local tileId = data[n]
      if tileId ~= 0
      then
        -- TODO REMOVE : remove "-1" after the bug is fixed in Tiled !
        local collisionFlags  = tileMap[tileId-1]
        -- TODO CHECK : check that the tileId returns something.
        collisionLayer[n] = collisionFlags
      else
        collisionLayer[n] = "0"
      end
      n = n + 1
    end -- for each tile n
  
    k = k + 1
  end -- for each layer k

  BnbCollisionMap = collisionMap
end

--[[
Used only for debug.
--]]
function dump()
  print "Dump collision map"
  print ""
  print (#BnbCollisionMap, "layers")

  for k,v in pairs(BnbCollisionMap)
  do
    print("Layer : ", k, v)
  end

  print "Data dump:"

  for layer,data in pairs(BnbCollisionMap)
  do
    print("Layer : ", layer)
    local n = 1
    local line = ""
    while (n <= #data)
    do
      line = line.." "..data[n]
      if ((n % BnbConstants.MapInfo.width) == 0) then
        print(line)
        line=""
      end
      n = n + 1
    end
  end
end

